let _Vue = null
export default class VueRouter {
  static install(Vue) {
    // 判断是否已经安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 把Vue构造函数记录到全局变量
    _Vue = Vue
    // 把创建Vue实例时候传入的router记录到Vue实例上
    Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  constructor(options) {
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
      current: window.location.hash.substring(1) || '/'
    })
  }
  
  createRouteMap() {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents(Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      methods: {
        clickHandler() {

        }
      },
      template: '<a :href="`#${to}`"><slot></slot></a>'
    })

    const _this = this
    Vue.component('router-view', {
      props: {

      },
      render(h) {
        const component = _this.routeMap[_this.data.current]
        return h(component)
      }
    })
  }

  initEvent() {
    window.addEventListener('hashchange', (e) => {
      this.data.current = e.currentTarget.location.hash.substring(1)
    })
  }

  init() {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }
}